package com.knife.oauth.domain.service.impl;

import com.knife.oauth.domain.entity.IamMemberRole;
import com.knife.oauth.domain.entity.IamUser;
import com.knife.oauth.domain.entity.KnifeUserDetails;
import com.knife.oauth.domain.service.AbstractKnifeUserDetailsBuilder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 构建 UserDetails
 *
 * @author： 76875
 * @date： 2022/4/13 星期三 11:00
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Component
public class DefaultKnifeUserDetailsBuilder extends AbstractKnifeUserDetailsBuilder {

    @Override
    public UserDetails buildUserDetails(IamUser tUser, List<IamMemberRole> roleList) {
        // 权限列表
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        // 赋予查询到的角色
        for (IamMemberRole tUserRole : roleList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(tUserRole.getRoleCode());
            authorities.add(authority);
        }
        // 创建UserDetails对象，设置用户名、密码和权限
        KnifeUserDetails knifeUserDetails = new KnifeUserDetails(tUser.getLoginName(), tUser.getHashPassword(), authorities);
        // 将用户数据转化为KnifeUserDetails
        knifeUserDetails.setLanguage(tUser.getLanguage());
        Assert.notEmpty(roleList, "请分配角色给用户");
        knifeUserDetails.setRoleId(roleList.get(0).getRoleId());
        knifeUserDetails.setRoleIds(roleList.stream().map(IamMemberRole::getRoleId).collect(Collectors.toList()));
        knifeUserDetails.setTenantId(tUser.getTenantId());
        knifeUserDetails.setTenantIds(Collections.singletonList(tUser.getTenantId()));
        knifeUserDetails.setImageUrl(tUser.getImageUrl());
        knifeUserDetails.setUserId(tUser.getId());
        knifeUserDetails.setRealName(tUser.getRealName());
        knifeUserDetails.setOrganizationId(tUser.getTenantId());
        knifeUserDetails.setTimeZone(tUser.getTimeZone());
        knifeUserDetails.setEmail(tUser.getEmail());
        knifeUserDetails.setAdmin(false);
        return knifeUserDetails;
    }

    @Override
    public void warp(UserDetails details) {

    }
}
